package com.example.mymultiactivityapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView

class SecondActivity4 : AppCompatActivity() {

    private lateinit var tvTimer: TextView
    private lateinit var btnStart: Button
    private lateinit var btnPause: Button
    private lateinit var btnReset: Button

    private var seconds = 0
    private var isRunning = false
    private var wasRunning = false

    private val handler = Handler(Looper.getMainLooper())
    private lateinit var runnable: Runnable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second4)

        initViews()
        setupClickListeners()

        if (savedInstanceState != null) {
            seconds = savedInstanceState.getInt("seconds")
            isRunning = savedInstanceState.getBoolean("isRunning")
            wasRunning = savedInstanceState.getBoolean("wasRunning")
        }

        runnable = Runnable {
            if (isRunning) {
                seconds++
                updateTimerDisplay()
            }
            handler.postDelayed(runnable, 1000)
        }
        handler.post(runnable)
    }

    private fun initViews() {
        tvTimer = findViewById(R.id.tv_timer)
        btnStart = findViewById(R.id.btn_start)
        btnPause = findViewById(R.id.btn_pause)
        btnReset = findViewById(R.id.btn_reset)
        updateTimerDisplay()
    }

    private fun setupClickListeners() {
        btnStart.setOnClickListener {
            isRunning = true
        }

        btnPause.setOnClickListener {
            isRunning = false
        }

        btnReset.setOnClickListener {
            isRunning = false
            seconds = 0
            updateTimerDisplay()
        }
    }

    private fun updateTimerDisplay() {
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val secs = seconds % 60
        val time = String.format("%02d:%02d:%02d", hours, minutes, secs)
        tvTimer.text = time
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("seconds", seconds)
        outState.putBoolean("isRunning", isRunning)
        outState.putBoolean("wasRunning", wasRunning)
    }

    override fun onPause() {
        super.onPause()
        wasRunning = isRunning
        isRunning = false
    }

    override fun onResume() {
        super.onResume()
        if (wasRunning) {
            isRunning = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(runnable)
    }
}